package com.zzzzzz.content.content;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.content.Constants;
import com.zzzzzz.content.article.ArticleService;
import com.zzzzzz.content.picitem.PicItemService;
import com.zzzzzz.content.userfeel.NoSuchUserFeelException;
import com.zzzzzz.content.userfeel.UserFeel;
import com.zzzzzz.content.userfeel.UserFeelAlreadyExistsException;
import com.zzzzzz.content.userfeel.UserFeelDao;

@Service("contentService")
public class ContentServiceImpl implements ContentService{

	@Resource
	private ContentDao contentDao;
	@Resource
	private ArticleService articleService;
	@Resource
	private PicItemService picItemService;
	@Resource
	private UserFeelDao userFeelDao;
	
	public List<ContentListView> find(String orderByField, int start, int offset){
		return contentDao.find(orderByField, start, offset);
	}
	
	public long findCount(){
		return contentDao.findByPicTextIdCount();
	}
	
	public List<ContentListView> findByTagId(Integer tagId, String orderByField, int start, int offset){
		return contentDao.findByTagId(tagId, orderByField, start, offset);
	}
	public long findByTagIdCount(Integer tagId){
		return contentDao.findByTagIdCount(tagId);
	}
	
	@Transactional
	public Integer like(Long id, Integer idType, Long userId) throws UserFeelAlreadyExistsException {
		try {
			userFeelDao.add(new UserFeel(id, idType, userId, Constants.FEEL_TYPE.LIKE));
			if(Constants.CONTENT_DB_TYPE.CONTENT == idType){
				articleService.editLikes(id, 1);
			}else if(Constants.CONTENT_DB_TYPE.PICITEM == idType){
				picItemService.editLikes(id, 1);
			}
		} catch (UserFeelAlreadyExistsException e) {
			return Constants.FEEL_RESULT.ALREADY_FEEL;
		}
		return Constants.FEEL_RESULT.OK;
	}
	
	@Transactional
	public Integer unFeel(Long id, Integer idType, Long userId) throws NoSuchUserFeelException {
		try {
			Integer feelType = userFeelDao.findFeelType(id, idType, userId);
			userFeelDao.del(new UserFeel(id, idType, userId, feelType));
			if(Constants.CONTENT_DB_TYPE.CONTENT == idType){
				articleService.editLikes(id, -1);
			}else if(Constants.CONTENT_DB_TYPE.PICITEM == idType){
				picItemService.editLikes(id, -1);
			}
			return Constants.FEEL_RESULT.OK;
		} catch (NoSuchUserFeelException e) {
			return Constants.FEEL_RESULT.NOSUCH_FEEL;
		}
	}
}
